/*
    Copyright 2010 Northbranchlogic, Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
 */

package com.norbl.runjrun;

import com.xerox.amazonws.ec2.*;
import com.norbl.util.*;
import java.io.*;
import java.util.*;
import com.norbl.util.s3.*;

/** A {@link RunnerNode} that runs on an ec2 instance.
 *
 * @author Barnet Wagman
 */
public class RunnerNodeEc2 extends RunnerNode {

    private HashMap<String,Integer> indexHt;

    public static void main(String[] argv) {
        try {           
            RunnerNodeEc2 lne = new RunnerNodeEc2();
            lne.run();
        }
        catch(Throwable x) {
            System.out.println(StringUtil.throwableToString(x));
        }
    }

    public RunnerNodeEc2() {
        super();
        indexHt = new HashMap<String,Integer>();
    }

    String getInstanceID() {
        try {
            return( EC2Utils.getInstanceMetadata("instance-id") );
        }
        catch(IOException iox) { throw new RunJRunException(iox); }
    }

    protected String getUserData() {
        try {
            return( EC2Utils.getInstanceUserdata() );
        }
        catch(Exception x) { throw new RunJRunException(x); }
    }

    protected void handleThrowable(Throwable xxx) {
        try {
            if ( s3Ops != null )
                s3Ops.addObject(params.exceptionBucketName,
                                buildThrowableS3Key(xxx),
                                xxx,true);
            else System.out.println(StringUtil.throwableToString(xxx));
        }
        catch(Throwable z) {
            System.out.println(StringUtil.throwableToString(z));
        }
    }

    String buildThrowableS3Key(Throwable x) {

        String s = params.exceptionS3KeyPrefix + "/";
        if ( x != null ) s += x.getClass().getSimpleName();
        else s += "null-throwable";

        if ( indexHt.size() > 1024 ) indexHt = new HashMap<String, Integer>();

        s += "-" + Time.toDateTimeMilliKeyString(System.currentTimeMillis());
        s += "-" + StringUtil.getNextIndex(indexHt,s);
        s += "." + S3Ops.GZSER;

        return(s);
    }
}
